<template>
  <div>
    <el-card>
      <!-- 面包屑 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商户管理</el-breadcrumb-item>
        <el-breadcrumb-item>轮播与广告</el-breadcrumb-item>
      </el-breadcrumb>
      <el-row type="flex" justify="space-between" class="mb-8">
        <el-col :span="12">
          <el-button icon="el-icon-plus" size="small" @click="addBanner">添加
          </el-button>
          <el-button icon="el-icon-delete" size="small" @click="delBanner">删除
          </el-button>
          <el-button icon="el-icon-upload2" size="small" @click="updateStatusBanner(1)">启用
          </el-button>
          <el-button icon="el-icon-download" size="small" @click="updateStatusBanner(0)">禁用
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-select class="style-right" size="small" v-model="bannerFlag" placeholder="全部" @change="getBanner()">
            <el-option value="-1" label="全部"></el-option>
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.text"
              :value="item.typeId"></el-option>
          </el-select>
          <div class="style-right2">
            <el-button size="small" @click="
              getBanner();
            bannerId = '';
            ">清空筛选</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 表格数据 -->
      <div>
        <!-- :cell-style="{'text-align':'center'}" -->
        <el-table border :data="dataList" @selection-change="selectChange" style="width: 100%;margin-top:8px;"
          height="70vh" :header-cell-style="{ background: '#409EFF', color: '#FFF' }">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="bannerId" label="编号" width="100">
          </el-table-column>
          <el-table-column prop="bannerName" label="图片名称" width="200">
            <template slot-scope="scope">
              <el-image style="width: 50px; height: 50px" :src="url + 'zhonghui/banner/' + scope.row.bannerName"
                fit="cover" :previewSrcList="[
                  url + 'zhonghui/banner/' + scope.row.bannerName,
                ]"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="bannerStatus" label="状态" width="200">
            <template slot-scope="scope">
              <el-tag type="warning" v-if="scope.row.bannerStatus == '0'">已禁用</el-tag>
              <el-tag type="success" v-else-if="scope.row.bannerStatus == '1'">已启用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="bannerHref" label="链接" width="200">
            <template slot-scope="scope">
              {{ scope.row.bannerHref | getHrefName }}
            </template>
          </el-table-column>
          <el-table-column prop="bannerPro" label="关联内容" width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.bannerHref == 'detail'">
                {{ scope.row.bannerPro | getproductName }}
              </span>
              <span v-if="scope.row.bannerHref == 'zqProduct'">
                {{ scope.row.bannerPro | getSpecialName }}
              </span>
              <span v-if="scope.row.bannerHref == 'forumKonwledge'">
                {{ scope.row.bannerPro | getTopicName }}
              </span>
              <span v-if="scope.row.bannerHref == 'videoDetail'">
                {{ scope.row.bannerPro | getVideoName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="bannerFlag" label="类型" width="120">
            <template slot-scope="scope">
              <el-tag>{{ scope.row.bannerFlag | getTypeName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="200">
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="200">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="small" type="primary" icon="el-icon-edit" @click="edit(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 弹窗页面 -->
      <el-dialog :title="popForm.flag == 'add' ? '添加' : '修改'" :visible.sync="addDialogVisible" width="30%"
        :before-close="cancelBox">
        <el-form ref="form" :model="popForm" label-width="80px" size="small" :rules="rules">
          <el-form-item label="图片" prop="file" ref="uploadRef">

            <img :src="url + 'zhonghui/banner/' + popForm.imgUrl" alt="" class="avarImg"
              v-if="popForm.flag == 'edit' && popForm.imgUrl != ''">

            <el-upload class="upload-demo" action="aa" :on-remove="picRemove" :on-change="picChange" list-type="picture"
              :auto-upload="false" name="file" accept="*" :limit="1" ref="addForm">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">*请上传小于2M的jpg文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="链接页面" prop="bannerHref">
            <el-select v-model="popForm.bannerHref" filterable placeholder="请选择" @change="selectPage">
              <el-option v-for="item in linkUrlArr" :key="item.urlId" :label="item.urlName"
                :value="item.urlLujing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联内容" prop="bannerPro" v-if="isShowSelectId">
            <el-select v-model="popForm.bannerPro" placeholder="请选择内容">
              <el-option v-for="(item, index) in selectList" :key="index" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型" prop="bannerFlag">
            <el-select v-model="popForm.bannerFlag" placeholder="请选择类型">
              <el-option v-for="(item, index) in typeList" :key="index" :label="item.text"
                :value="item.typeId"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="bannerStatus">
            <el-select v-model="popForm.bannerStatus" placeholder="请选择状态">
              <el-option label="禁用" value="0"></el-option>
              <el-option label="启用" value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="上架时间" prop="startTime">
            <el-date-picker align="right" v-model="popForm.startTime" type="datetime" placeholder="请选择上架日期"
              value-format="yyyy-MM-dd HH:mm:ss" style="width: 215px;"></el-date-picker>
          </el-form-item>
          <el-form-item label="下架时间" prop="endTime">
            <el-date-picker align="right" v-model="popForm.endTime" type="datetime" placeholder="请选择下架日期"
              value-format="yyyy-MM-dd HH:mm:ss" style="width: 215px;"></el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelBox">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 页码 -->
      <div class="pagination-control">
        <el-pagination :page-sizes="[20, 50, 80, 100]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="sizeChange"
          @current-change="currentChange"></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
let that
import { url } from "../../network/request";
import {
  getBanner,
  delBanner,
  updateStatusBanner,
  getLinkUrl2,
  submitAddBanner,
} from "../../network/banner";
import { listProduct } from "../../network/product";
import {
  getProductSpecials,
} from 'network/specials'
import { getTopicPage } from '../../network/content'



export default {
  data() {
    return {
      url,
      dataList: [],
      pageSize: 20,
      totalCount: 0,
      pageNumber: 1,
      popForm: {
        bannerId: "",
        bannerStatus: "",
        bannerHref: "",
        bannerPro: "",
        bannerFlag: "",
        shopId: "",
        startTime: "",
        endTime: "",
        flag: "",
        file: "",
      },
      addDialogVisible: false,
      linkUrlArr: [],
      urlStatus: "",
      selectVal: "",
      bannerFlag: "-1",
      checkList: [],
      isShowSelectId: false,
      productList: [],
      specilaList: [],
      topicList: [],
      videoList: [],
      selectList: [],

      rules: {
        bannerHref: [{ required: true, message: '请选择相关链接', trigger: 'change' }],
        bannerPro: [{ required: true, message: '请选择关联内容', trigger: 'change' }],
        bannerFlag: [{ required: true, message: '请选择轮播图类型', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择上架日期', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择下架日期', trigger: 'change' }]
      },

      typeList: [
        {
          typeId: 0,
          text: '首页轮播图'
        },
        // {
        //   typeId: 1,
        //   text: '论坛轮播图'
        // },
        // {
        //   typeId: 2,
        //   text: '首页广告位'
        // },
        // {
        //   typeId: 3,
        //   text: '论坛广告位'
        // },
        //   {
        //     typeId: 4,
        //     text: '首页弹窗'
        //   },
        //   {
        //     typeId: 5,
        //     text: '论坛弹窗'
        //   },
        //   {
        //     typeId: 6,
        //     text: '启动页广告图'
        //   },
      ]


    };
  },
  created() {
    this.getBanner();
    this.getProductList()
    this.getLink()
    this.getData()
    this.getTopicList()
    that = this

  },

  methods: {
    getTopicList() {
      getTopicPage({
        page: 1,
        size: 500,
        topicFlag: 0,
        topicTitle: ''
      }).then(res => {
        if (res.flag) {
          console.log(res.data);
          this.topicList = []
          this.videoList = []
          res.data.list.forEach(ele => {
            if (ele.topicFlag == 0) {
              this.topicList.push(ele)
            } else {
              this.videoList.push(ele)
            }
          })
        }
      })
    },

    // 获取全部商品
    getProductList() {
      listProduct({
        shopId: '',
        size: 500,
        page: 1,
        productName: '',
        productStatus: '-1'
      }).then(res => {
        console.log(res);
        if (res.flag) {
          this.productList = res.data.list
        }
      })
    },
    getData() {
      getProductSpecials({
        flag: 0
      }).then(res => {
        console.log(res);
        if (res.flag) {
          this.specilaList = res.data
        }
      })
    },

    // 用flag来传递顶部的参数 0 还是 1
    updateStatusBanner(flag) {
      // 用长度来判断
      if (this.checkList.length == 0) {
        this.$message.warning("请选择操作的数据");
        return;
      }
      console.log(this.checkList);
      // 定义一个空的ids
      var ids = "";
      // 遍历这个选择的列表数组，根据其bannerId来判断，并且通过","来区分

      this.checkList.forEach((item) => {
        ids += item.bannerId + ",";
      }
      );
      updateStatusBanner({
        ids: ids,
        // flag 是
        bannerStatus: flag,
      })
        .then((res) => {
          if (res.flag) {
            this.getBanner();
            this.$message.warning("更新状态成功");
          }
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });

      console.log(ids);
    },
    // 获取数据
    getBanner() {
      console.log(this.bannerFlag);
      getBanner({
        bannerFlag: this.bannerFlag,
        page: this.pageNumber,
        size: this.pageSize,
      })
        .then((res) => {
          console.log(res);
          this.dataList = res.data.list;
          this.totalCount = res.data.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 弹框
    cancelBox() {
      this.$refs.form.resetFields();
      this.$refs.addForm.clearFiles();
      this.addDialogVisible = false;
    },
    // 添加
    addBanner() {
      this.addDialogVisible = true;
      this.popForm = {
        bannerId: "",
        bannerStatus: "1",
        bannerHref: "",
        bannerPro: "",
        bannerFlag: "",
        shopId: 0,
        startTime: "",
        endTime: "",
        flag: "add",
        file: "",
      };
    },

    getLink() {
      getLinkUrl2({
        shopId: this.shop_id,
      })
        .then((res) => {
          this.linkUrlArr = res.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //修改编辑
    edit(row) {
      console.log(row);
      getLinkUrl2({
        shopId: 0,
      })
        .then((res) => {
          this.linkUrlArr = res.data;
          this.addDialogVisible = true;
          this.popForm = {
            bannerId: row.bannerId,
            bannerStatus: row.bannerStatus + "",
            bannerHref: row.bannerHref,
            bannerPro: row.bannerPro,
            bannerFlag: row.bannerFlag,
            shopId: 0,
            startTime: row.startTime,
            endTime: row.endTime,
            flag: "edit",
            imgUrl: row.bannerName
          };
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 删除
    delBanner() {
      if (this.checkList.length === 0) {
        return this.$message.warning("请勾选要删除的数据");
      }
      let bannerId = "";
      for (let i = 0; i < this.checkList.length; i++) {
        bannerId += this.checkList[i].bannerId + ",";
      }
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delBanner({
            ids: bannerId,
          })
            .then((res) => {
              if (res.flag) {
                this.getBanner();
                this.$message.success("成功");
              } else {
                this.$message.error("失败");
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },


    // 选择
    selectPage(val) {
      this.isShowSelectId = val == "detail" || val == "zqProduct" || val == 'forumKonwledge' || val == 'videoDetail';

      this.selectList = []

      this.popForm.bannerPro = ''

      if (val == "detail") {
        // 获取商品
        this.productList.forEach(ele => {
          this.selectList.push({
            id: ele.productId,
            name: ele.productName
          })
        })
      } else if (val == "zqProduct") {
        // 获取专区
        this.specilaList.forEach(ele => {
          this.selectList.push({
            id: ele.specialId,
            name: ele.specialName
          })
        })
      } else if (val == "forumKonwledge") {
        // 获取文章列表
        this.topicList.forEach(ele => {
          this.selectList.push({
            id: ele.topicId,
            name: ele.topicTitle
          })
        })
      } else if (val == "videoDetail") {
        // 获取视频列表
        this.videoList.forEach(ele => {
          this.selectList.push({
            id: ele.topicId,
            name: ele.topicTitle
          })
        })
      }

    },

    // 上传图片
    picRemove(file, fileList) { },
    picChange(file, fileList) {

      if (this.popForm.flag == 'edit') {
        this.popForm.imgUrl = ''
      }

      this.popForm.file = file.raw;
    },

    // 提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {


          if (this.popForm.flag == 'add' && this.popForm.file == '') {
            this.$message.warning('请上传图片')
            return
          }
          if (this.popForm.flag == 'edit' && this.popForm.imgUrl == '' && this.popForm.file == '') {
            this.$message.warning('请上传图片')
            return
          }

          console.log(this.popForm);

          let sub = new FormData();
          sub.append("bannerStatus", this.popForm.bannerStatus);
          sub.append("bannerHref", this.popForm.bannerHref);
          sub.append("bannerPro", this.popForm.bannerPro);
          sub.append("bannerFlag", this.popForm.bannerFlag);
          sub.append("shopId", sessionStorage.shop_id);
          sub.append("startTime", this.popForm.startTime);
          sub.append("endTime", this.popForm.endTime);
          sub.append("flag", this.popForm.flag);

          if (this.popForm.flag == 'add') {
            sub.append("file", this.popForm.file);
          } else {
            sub.append('bannerId', this.popForm.bannerId)
            if (this.popForm.imgUrl == '') {
              sub.append("file", this.popForm.file);
            } else {
              sub.append("file", this.popForm.imgUrl);
            }
          }

          console.log(this.popForm);
          submitAddBanner(sub).then((res) => {
            console.log(res);
            if (res.flag) {
              this.getBanner();
              this.cancelBox();
              this.$message.success("上传成功");
            } else {
              console.log(res);
              this.$message.success("上传失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 点击数据
    selectChange(val) {
      this.checkList = val;
    },

    //每页N条发生改变
    sizeChange(val) {
      this.pageSize = val;
      this.loading = true;
      this.getBanner();
    },
    // 页码发生改变
    currentChange(val) {
      this.pageNumber = val;
      this.loading = true;
      this.getBanner();
    },
  },
  filters: {
    getproductName: function (id) {
      var name = '';
      that.productList.forEach(ele => {
        if (ele.productId == id) {
          name = ele.productName
        }
      })
      return name;
    },

    getSpecialName: function (id) {
      var name = '';
      that.specilaList.forEach(ele => {
        if (ele.specialId == id) {
          name = ele.specialName
        }
      })
      return name;
    },
    getTopicName: function (id) {
      var name = '';
      that.topicList.forEach(ele => {
        if (ele.topicId == id) {
          name = ele.topicTitle
        }
      })
      return name;
    },
    getVideoName: function (id) {
      var name = '';
      that.videoList.forEach(ele => {
        if (ele.topicId == id) {
          name = ele.topicTitle
        }
      })
      return name;
    },
    getTypeName: function (id) {
      var name = '';
      that.typeList.forEach(ele => {
        if (ele.typeId == id) {
          name = ele.text
        }
      })
      return name;
    },
    getHrefName: function (text) {
      var name = '';
      that.linkUrlArr.forEach(ele => {
        if (ele.urlLujing == text) {
          name = ele.urlName
        }
      })
      return name;
    },
  },
};
</script>
<style>
body {
  position: relative;
  right: 0;
}

.style-right {
  position: absolute;
  right: 100px;
  margin-bottom: 10px;
}

.style-right2 {
  position: absolute;
  right: 0;
}

.mb-8 {
  margin-bottom: 8px;
}


.avarImg {
  width: 120px;
  height: 120px;
}
</style>
